package com.scpii.api.service.push.apns;

import java.util.ArrayList;
import java.util.List;

import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

public class ApnsSendDemo {

	private static Log logger = LogFactory.getLog(ApnsSendDemo.class);

	private static ObjectMapper objectMap = new ObjectMapper();

	public static void main(String[] args) throws Exception {

		AppleMessage appleMessage = new AppleMessage();
		String s = "IOS 推送demo测试";
		appleMessage.getAps().setAlert("你的订单已发货{\"aps\":{\"alert\":\"" + s + "\",\"messageId\":465}}");
		String message = objectMap.writeValueAsString(appleMessage);

		logger.info("打印推送信息体:" + message);

		PushNotificationPayload payLoad = PushNotificationPayload.fromJSON(message);
		payLoad.addBadge(2000000); // 图标小红圈的数值
		payLoad.addSound("default"); // 铃音 默认
		PushNotificationManager pushManager = new PushNotificationManager();
		String p12 = "C:\\Users\\yue\\Desktop\\apn_developer_identify.p12";
		p12 = "C:\\Users\\Estn\\Desktop\\111000001268.p12";
		try {
			pushManager.initializeConnection(new AppleNotificationServerBasicImpl(p12, "fhzx!@#123", true));
		} catch (CommunicationException e1) {
			e1.printStackTrace();
		} catch (KeystoreException e1) {
			e1.printStackTrace();
		}

		List<String> tokens = new ArrayList<String>();
		// 4e80116c44531a2e5f1aca88938d7836cfbafed274142e06e9e1804ad928d360  --》柳波的iphone
		// c799de3b9b5e734d7c3cb3e9227e66d44e07fc55b62ee0d405f51bfb883583cc  白色破解机子
		tokens.add("4e80116c44531a2e5f1aca88938d7836cfbafed274142e06e9e1804ad928d360");

		List<Device> device = new ArrayList<Device>();
		for (String token : tokens) {
			try {
				device.add(new BasicDevice(token));
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		List<PushedNotification> notifications = pushManager.sendNotifications(payLoad, device);
		PushedNotification ps = notifications.get(0);

		pushManager.stopConnection();

		List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);
		logger.info("此次总计发送数量：" + tokens.size() + "    失败发送：" + failedNotifications.size());

	}

}
